package com.gitee.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import com.gitee.annotation.Log;

/**
 * 自定义日志注解AOP基类
 * 
 * @author 赵炎
 * @version [V1.00, 2019年1月23日]
 * @since V1.00
 */
public abstract class BaseLogAspect
{
    
    /**
     * 切点 日志注解类
     */
    @Pointcut("@annotation(com.gitee.annotation.Log)")
    public void logPointcut()
    {
    }
    
    /**
     * 正常请求
     * 
     * @param joinPoint
     */
    @AfterReturning("logPointcut()")
    public void doBefore(JoinPoint joinPoint)
    {
        handleLog(joinPoint, getAnnotation(joinPoint), null);
    }
    
    /**
     * 出现异常
     * 
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointcut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e)
    {
        handleLog(joinPoint, getAnnotation(joinPoint), e);
    }
    
    /** 
     * 继承此类需要实现改方法
     * @param joinPoint 切点
     * @param log LOG
     * @param e 异常
     */
    public abstract void handleLog(JoinPoint joinPoint, Log log, Exception e);
    
    
    /**
     * 获取日志注解方法
     * 
     * @param joinPoint
     * @return
     */
    private Log getAnnotation(JoinPoint joinPoint)
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method method = methodSignature.getMethod();
        if (method != null)
        {
            return method.getAnnotation(Log.class);
        }
        return null;
    }
}
